package com.chujian.Activities;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;

import za.co.immedia.pinnedheaderlistview.PinnedHeaderListView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.chujian.Adapter.MapSectionAdapter;
import com.chujian.Global.Global;
import com.chujian.Threads.HttpClientGetThread;
import com.chujian.model.Food;
import com.chujian.orderingsystem.R;
import com.chujian.orderingsystem.R.color;

/**
 * 实现点餐功能
 * @author 周映凯
 *
 */
public class TakeOrderActivity extends Activity implements OnClickListener{
	
	
	private boolean isScroll = true;
	
	private ListView left_listView;
	private static Handler mHandler;
	MapSectionAdapter sectionedAdapter;
	PinnedHeaderListView right_listview;
	private Button btn_yixuan;
	private Button mBtnTable;
		
//	临时测试
	List<Food> lf=new ArrayList<Food>();
/**
 * 需要传送的数据：
 * 1.图片
 * 2.菜品类别
 * 3.菜品名称
 * 4.销量
 * 5.点赞数
 * 6.单价
 * 7.单位
 * 8.评价信息（可选）
 */
//	section 菜品类别
	Set<String> categarySet=new HashSet<String>();
	private List<String> leftStrList=new ArrayList<String>();
	Map<String , List<Food>> rightStrMap=new HashMap<String, List<Food>>();
	List<String> rightItem;
	String []array;
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		btn_yixuan.setText("已选菜品（"+Global.count+"）");
		if(Global.count<=0){
			btn_yixuan.setClickable(false);
			btn_yixuan.setBackgroundColor(Color.parseColor("#cccccc"));
		}
	}
	private void initView() {
		// TODO Auto-generated method stub
		 	btn_yixuan=(Button) findViewById(R.id.btn_yixuancp);
	        mBtnTable=(Button) findViewById(R.id.btn_table_selected);
	  		btn_yixuan.setOnClickListener(this);
	  		mBtnTable.setOnClickListener(this);
	  		mBtnTable.setText(Global.selectedTable);
	  		if(Global.count<=0){
	  			btn_yixuan.setClickable(false);
			}else{
				btn_yixuan.setBackgroundResource(R.drawable.yellow_button_selector);
			}
	  		
	        right_listview=(PinnedHeaderListView) findViewById(R.id.pinnedListView);
	   	 	left_listView = (ListView) findViewById(R.id.left_listview);
	   	 	left_listView.setBackgroundColor(Color.rgb(248, 248, 248));
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_order);
        initView();

        
        
	   	mHandler=new Handler(){
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				String str=(String)msg.obj;
				getlistForJson(str);
			    sectionedAdapter = new MapSectionAdapter(TakeOrderActivity.this, leftStrList, rightStrMap,btn_yixuan);
			    right_listview.setAdapter(sectionedAdapter);
			    left_listView.setAdapter(new ArrayAdapter(TakeOrderActivity.this, android.R.layout.simple_expandable_list_item_1, leftStrList));
			};
		};
//   	 连接服务器
       String url = "http://192.168.23.1:8080/OrderSystemServer/MenuServlet";
       new HttpClientGetThread(url, mHandler).start();
        
       
      
//       left_listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, leftStrList));
       left_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
				isScroll = false;
// 				对被单击到的左边listview item进行处理
				for (int i = 0; i < left_listView.getChildCount(); i++)
				{
					if (i == position)
					{
//						单击到的item设置背景为白色
						left_listView.getChildAt(i).setBackgroundColor(Color.rgb(255, 255, 255));
					} else
					{
						left_listView.getChildAt(i).setBackgroundColor(Color.rgb(248, 248, 248));
					}
				}

				int rightSection = 0;
				for(int i=0;i<position;i++){
//					获取右边子项的长度
					rightSection += sectionedAdapter.getCountForSection(i)+1;
				}
				right_listview.setSelection(rightSection);
				
			}

		});
        
        right_listview.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				if(isScroll){
					for (int i = 0; i < left_listView.getChildCount(); i++)
					{
//						根据右边listview第一个可见的item得到左边对应的item的下标。
						if (i == sectionedAdapter.getSectionForPosition(firstVisibleItem))
						{
							left_listView.getChildAt(i).setBackgroundColor(Color.rgb(255, 255, 255));
						} else
						{
							left_listView.getChildAt(i).setBackgroundColor(Color.rgb(248, 248, 248));

						}
					}
						
				}else{
					isScroll = true;
				}
			}
		});
        
    }

 

	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
	

/**
	 * Json 转成 Map<>
	 * @param jsonStr
	 * @return
	 */
	public  Map<String, List<Food>> getMapForJson(String jsonStr){
		JSONObject jsonObject ;
		try {
			jsonObject = new JSONObject(jsonStr);
			
			Iterator<String> keyIter= jsonObject.keys();
			String key;
			Object value ;
			Map<String, List<Food>> valueMap = new HashMap<String, List<Food>>();
			while (keyIter.hasNext()) {
				key = keyIter.next();
//				***
				categarySet.add(key);
//				****
				JSONArray array=jsonObject.getJSONArray(key);
				List<Food>foodList=new ArrayList<Food>();
                for(int j=0;j<array.length();j++){
                	JSONObject obj=array.getJSONObject(j);
	               	Food food=new Food();
	               	food.setFoodCategary(obj.getString("foodCategary"));
	               	food.setFoodName(obj.getString("foodName"));
	               	food.setFoodPrice((float)obj.getDouble("foodPrice"));
	               	food.setFoodStatus(obj.getString("foodStatus"));
	               	food.setFoodUnit(obj.getString("foodUnit"));
	               	food.setFoodUrl(obj.getString("foodUrl"));
	               	food.setFoodZan(obj.getInt("foodZan"));
	               	food.setSellCount(obj.getInt("sellCount"));
	               	food.setFoodCai(obj.getInt("foodCai"));
	               	foodList.add(food);
//	               	临时添加
	               	lf.add(food);
                }
                
                valueMap.put(key, foodList);
			}
//			***********
			rightStrMap=valueMap;
//			********
			return valueMap;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			Log.e("log.e", e.toString());
		}
		return null;
	}
	/**
	 * Json 转成 List<Map<>>
	 * @param jsonStr
	 * @return
	 */
	public  List<Map<String, List<Food>>> getlistForJson(String jsonStr){
		List<Map<String, List<Food>>> list = null;
		try {
			JSONArray jsonArray = new JSONArray(jsonStr);
			JSONObject jsonObj ;
			list = new ArrayList<Map<String,List<Food>>>();
			for(int i = 0 ; i < jsonArray.length() ; i ++){
				jsonObj = (JSONObject)jsonArray.get(i);
				list.add(getMapForJson(jsonObj.toString()));
			}
//			**************
			Iterator<String> it=categarySet.iterator();
			while(it.hasNext()){
				leftStrList.add(it.next());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Global.add_food_flag=false;
		Global.selectedTable=null;
		Global.orderAddId=null;
		
		super.onDestroy();
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==3001&&requestCode==2001){
//			String newAddOrder=data.getStringExtra("newAddOrder");
//			Intent intent=new Intent();
			setResult(3002, data);
			finish();
		}
		
	};
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_yixuancp:
			Intent intent =new Intent(TakeOrderActivity.this, YixuanCaipinActivity.class);
//			intent.putExtra("listFood", (Serializable)lf);
			startActivityForResult(intent, 2001);
			
			
			break;
		case R.id.btn_table_selected:
			
			break;
		default:
			break;
		}
	}
	
	public void IbBack(View v){
		finish();
	}
}
